import { defineStore } from 'pinia'
import { useRequest } from '~/composables/useRequest'
import { isGateApp } from '~/utils'

export const useMetaStore = defineStore('metaStore', () => {
  const { requestGetNew, requestPost } = useRequest()
  const channelData = useMyStorage('channelData', {})
  const paymentList = useMyStorage('paymentList', [])
  const currencyList = useMyStorage('currencyList', [])
  const curCurrency = useMyStorage('curCurrency', {})
  return {
    paymentList,
    currencyList,
    curCurrency,
    channelData,
    async initPaymentList(goodsSkuId) {
      const { payments, channelDto } = await requestGetNew(
        '/app/currency/allPayments',
        {
          currencyId: curCurrency.value?.id,
          isGateApp: isGateApp(),
          goodsSkuId,
        },
        { withAuth: true },
      )
      paymentList.value = payments ?? []
      channelData.value = channelDto
    },
    async initCurrency(lang?: string) {
      const data = await requestGetNew(
        '/app/currency/allCurrency',
        {
          uri: process.client ? encodeURIComponent(location.href) : '',
        },
        { hideError: true, headers: lang ? { lang } : undefined },
      )
      currencyList.value = data ?? []
      const localCurrency = process.client && +localStorage.getItem('currencyId')
      const isExistId = currencyList.value.some((item) => item.id === localCurrency)
      this.setCurCurrencyId(isExistId ? localCurrency : currencyList.value[0]?.id)
    },
    setCurCurrencyId(id) {
      if (!id) return
      process.client && localStorage.setItem('currencyId', id)
      curCurrency.value = currencyList.value.find((item) => item.id === +id) ?? {}
    },
  }
})
